package org.vaadinpa.logic;

import java.util.Date;
import java.util.Map;
import java.util.WeakHashMap;

public class Ticker {

	private static TickThread ticker = new TickThread();
	private static CountdownThread countdown;
	public static boolean suspended;
	public static int currentTick;

	/**
	 * Set of tick listeners
	 */
	private static Map<TickListener, Object> listeners = new WeakHashMap<TickListener, Object>();

	public static void startTicksAfter(long millis) {
		countdown = new CountdownThread(millis);
		countdown.start();

		fireScheduleEvent();
	}

	public static Date getSecondsUntilTickStart() {

		if (countdown != null && countdown.isAlive()) {
			return countdown.getStartTime();
		}
		return null;
	}

	public static boolean areTicksRunning() {
		return ticker == null ? false : ticker.isAlive();
	}

	public static void startTicks() {
		if (ticker == null || !ticker.isAlive()) {
			ticker = new TickThread();
			ticker.start();

			fireStartEvent();

			System.out.println("Started ticker thread");
		}
	}

	public static void endTicks() {
		if (ticker != null) {
			ticker.interrupt();
			ticker = null;

			fireEndEvent();

			System.out.println("Interrupted ticker thread");
		}
	}

	public static void addListener(TickListener l) {

		synchronized (listeners) {
			listeners.put(l, null);
		}
	}

	public static void removeListener(TickListener l) {

		synchronized (listeners) {
			listeners.remove(l);

			if (listeners.isEmpty()) {
				Ticker.endTicks();
			}
		}
	}

	static void fireTickEvent() {
		for (TickListener tl : listeners.keySet()) {
			tl.tickOccurred();
		}
	}

	private static void fireStartEvent() {
		for (TickListener tl : listeners.keySet()) {
			tl.ticksStarted();
		}
	}

	private static void fireEndEvent() {
		for (TickListener tl : listeners.keySet()) {
			tl.ticksEnded();
		}
	}

	private static void fireScheduleEvent() {
		for (TickListener tl : listeners.keySet()) {
			tl.ticksStartScheduled();
		}

	}
}
